#include <bits/stdc++.h>

using namespace std;
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right)
        : val(x), left(left), right(right) {}
};

class Solution {
   public:
    int ret = 0;
    void dfs(TreeNode* root, int low, int high) {
        if (!root) {
            return;
        }
        if (root->val < low) {
            dfs(root->right, low, high);
            return;
        }
        if (root->val > high) {
            dfs(root->left, low, high);
            return;
        }
        ret += root->val;
        dfs(root->left, low, high);
        dfs(root->right, low, high);
    }
    int rangeSumBST(TreeNode* root, int low, int high) {
        dfs(root, low, high);
        return ret;
    }
};